package com.fierce.cloud.ota.controller;

import com.fierce.cloud.core.web.ResultGenerator;
import com.fierce.cloud.core.web.responseDto.Response;
import com.fierce.cloud.ota.model.AppInfo;
import com.fierce.cloud.ota.model.VersionInfo;
import com.fierce.cloud.ota.model.responseVo.ApplicationInfoVo;
import com.fierce.cloud.ota.service.AppInfoService;
import com.fierce.cloud.ota.service.VersionInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javafx.application.Application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Fierce
 * @Date: 2021/2/26 10:59
 */
@RestController
@RequestMapping("/application")
public class AppController {

    @Resource
    AppInfoService appInfoService;

    @Autowired
    VersionInfoService versionInfoService;

    /**
     * 保存更新应用信息
     *
     * @param appInfo
     * @return
     */
    @PostMapping("/save")
    public Response createApplication(AppInfo appInfo) {
        if (appInfo.getId() != null && appInfoService.findById(appInfo.getId()) != null) {
            appInfoService.update(appInfo);
            return ResultGenerator.genSuccessResult("更新成功");
        } else {
            appInfoService.save(appInfo);
            return ResultGenerator.genSuccessResult("创建成功");
        }
    }

    /**
     * 分页查询指定用户下的应用列表
     *
     * @param userId
     * @return
     */
    @GetMapping("/list")
    public Response<List<AppInfo>> getAppInfoList(Long userId) {
        Example example = new Example(AppInfo.class);
        example.createCriteria().andEqualTo("userId", userId);
        List<AppInfo> appInfoList = appInfoService.findByExample(example);
        return ResultGenerator.genSuccessResult(appInfoList);
    }

    /**
     * 获取指定应用的信息
     *
     * @param appId
     * @return
     */
    @GetMapping("/info/{appId}")
    public Response<ApplicationInfoVo> getAppInfo(@PathVariable Long appId) {
        AppInfo appInfo = appInfoService.findById(appId);
        ApplicationInfoVo applicationInfoVo = new ApplicationInfoVo();
        applicationInfoVo.setAppName(appInfo.getAppName());
        applicationInfoVo.setPlatform(appInfo.getPlatform());
        applicationInfoVo.setCategory(appInfo.getCategory());
        VersionInfo newestVersionByAppId = versionInfoService.getNewestVersionByAppId(appId);
        applicationInfoVo.setVersionCode(newestVersionByAppId == null ? -1 : newestVersionByAppId.getVersionCode());
        return ResultGenerator.genSuccessResult(applicationInfoVo);
    }

    @PostMapping("/delete")
    public Response deleteOneApplication(Long appId) {
        appInfoService.deleteById(appId);
        return ResultGenerator.genSuccessResult("删除成功");
    }
}
